package cn.lkx.serviceoss.service.impl;

import cn.lkx.serviceoss.service.OssService;
import cn.lkx.serviceoss.utils.PropertiesUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadAvatar(MultipartFile file) {
        //工具类获取值
        String endpoint = PropertiesUtil.END_POINT;
        String accessKeyId = PropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = PropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = PropertiesUtil.BUCKET_NAME;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            //获取文件上传输入流
            InputStream inputStream = file.getInputStream();

            //获取文件名称，真实上传的文件名
            String fileName = file.getOriginalFilename();
            //加上UUID防止相同名称的文件被覆盖
            fileName = UUID.randomUUID().toString() + fileName;
            //把文件按日期进行分类管理
            String datePath = new DateTime().toString("yyyy/MM/dd");
            // 2022/5/2/eadqtt214502.jpg
            fileName = datePath + "/" + fileName;

            // 调用oss方法实现上传 第二个参数：上传到oss的文件路径和文件名称
            ossClient.putObject(bucketName, fileName, inputStream);
            //把上传之后的文件路径返回，需要手动拼接
            //https://edu-2022-5.oss-cn-beijing.aliyuncs.com/t010caca5d99729b1ed.webp
            String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {  //关闭
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
